<template>
  <div class="add">
    <el-dialog :title="title" :visible="show" width="30%" @close="closeEvent">
      <el-form ref="form" label-width="80px" :rules="rules" :model="form">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEvent">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { sysRolePost, sysRolePut } from '@/api/setter'
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      mode: 'add',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            min: 1,
            max: 12,
            message: '请输入1~12的正确字符',
            trigger: 'change'
          }
        ],
        description: [
          { required: true, message: '必填', trigger: 'change' },
          {
            min: 1,
            max: 30,
            message: '请输入1~30的正确字符',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    title() {
      return { add: '新增', edit: '编辑' }[this.mode]
    }
  },
  methods: {
    closeEvent() {
      this.$emit('update:show', false)
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    submit() {
      this.$refs.form.validate(async(val) => {
        if (val) {
          if (this.mode === 'add') {
            await sysRolePost(this.form)
          } else if (this.mode === 'edit') {
            await sysRolePut(this.form)
          }
          this.$message.success('成啦！')
          this.closeEvent()
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
